<?php require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "function.php";
$type = !empty($_GET['type']) ? htmlspecialchars($_GET['type']) : "1"; //报修类型
$apply_device_id = !empty($_GET['apply_device_id']) ? htmlspecialchars($_GET['apply_device_id']) : "1"; //报修设备id

function getTypeName2($mid)
{
    global $dosql;
    if ($mid > 0) {
        $m = $dosql->GetOne("SELECT * FROM `#@__cascadedata` WHERE   datagroup='device' AND  datavalue='$mid'  ORDER BY id desc");
        if (is_array($m) && isset($m['id'])) {
            return $m['dataname'];
        }
    }
}


?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>扫码报修-<?php echo $cfg_webname; ?></title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="description" content="<?php echo $cfg_webname; ?>">
        <link rel="stylesheet" href="lib/weui.min.css">
        <link rel="stylesheet" href="css/jquery-weui.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">
        <link rel="stylesheet" href="css/demos.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap.min.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap-theme.min.css">
        <script src="lib/jquery-2.1.4.js"></script>
        <script src="lib/fastclick.js"></script>
        <script>
            $(function () {
                FastClick.attach(document.body);
            });
        </script>
        <script src="js/jquery-weui.js"></script>
        <script src="js/city-picker.js"></script>
        <style>
            label {
                font-weight: normal;
                color: #00aeef;
                font-size: 0.92em;
            }
        </style>
    </head>
<body ontouchstart>
<div class="top"><a href="index.php"><img src="images/top.jpg" width="100%"></a></div>
<?php
$sn_num = "";
if (!isset($action)) {
//获取参数中的条形码
    $ma = htmlspecialchars($_GET['sn']);
    $sn_num = ""; //设备序列号
    $apply_name = ""; // 设备名称
    $typeidid = "1";
    if (isset($ma)) {
        $sn_num = $ma; //设备序列号
        //从数据库中查询 设备序列号
        $row_sn = $dosql->GetOne("SELECT * FROM `#@__sn` WHERE `sn`='$sn_num' ");
        $school_sn = "";
        $truename_sn = "";
        $mobile_sn = "";
        $address_sn = "";
        $typename_sn = "";
        if (is_array($row_sn) && isset($row_sn['id'])) {
            $school_sn = $row_sn['school'];
            $mobile_sn = $row_sn['mobile'];
            $typename_sn = $row_sn['typename'];
            $typename_text = getTypeName2($row_sn['typename']);
            $model_sn = $row_sn['model'];
            $title_sn = $row_sn['title'];
            $country_sn = $row_sn['country'];
            $school_sn = $row_sn['school'];
            $town = $row_sn['country'];

            // 过期时间
            $guoqi = $row_sn['end_time'] + 86400;
            if (time() > $guoqi) {
                echo '<script type="text/javascript">$.alert("设备已经过保，保外产品维修会产生费用。","温馨提示");
				</script>';
            }
        } else {
            echo '<script type="text/javascript">$.alert("您扫描的二维码不在条形码库，请您与客服人员联系沟通。");
			</script>';
        }

    }
}
?>
<!-- 地址信息 -->
<form name="form" id="form" method="post" action="">
    <div class="main bg-info">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i>扫码报修信息</div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label"> 联系人： <span
                            class="red">*</span></label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" name="truename" id="truename" type="text"
                       value="">
            </div>
        </div>
        <div class="weui-cell ">
            <div class="weui-cell__hd">
                <label class="weui-label">手机号： <span
                            class="red">*</span></label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" name="mobile" id="mobile" type="text" value="">
            </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label">地址：</label>
            </div>
            <div class="weui-cell__bd">
                <input class="form-control" type="text" name="address" id="address"
                       value="">
            </div>
        </div>


        <input type="hidden" id="latitude" name="latitude">
        <input type="hidden" id="longitude" name="longitude">
        <input type="hidden" id="accuracy" name="accuracy">
        <input type="hidden" name="address_name" id="address_name" value="">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label for="" class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>使用单位：</label>
                </div>
                <div class="weui-cell__bd">
                    <input class="form-control" name="school" id="school" type="text" readOnly="true"
                           value="<?php echo $school_sn; ?>">
                    <input class="form-control" name="town" id="town" type="hidden" readOnly="true"
                           value="<?php echo $town; ?>">
                </div>
            </div>
            <!--            <div class="weui-cell">-->
            <!--                <div class="weui-cell__hd">-->
            <!--                    <label for="" class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>设备类型：</label>-->
            <!--                </div>-->
            <!--                <div class="weui-cell__bd">-->
            <!--                   -->
            <!--                </div>-->
            <!--            </div>-->
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>序列号：</label>
                </div>
                <div class="weui-cell__bd">
                    <input class="form-control" name="typename" id="typename" type="hidden" readOnly="true"
                           value="<?php echo $typename_sn; ?>">
                    <input class="form-control" name="device_num" id="device_num" type="text" readOnly="true"
                           value="<?php echo $sn_num; ?>">
                </div>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>设备：</label>
                </div>
                <div class="weui-cell__bd">
                    <input class="form-control" name="title" id="title" type="text" readOnly="true"
                           value="<?php echo $title_sn; ?>">
                </div>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>类型：</label>
                </div>
                <div class="weui-cell__bd">

                    <input class="form-control" name="typename_text" id="typename_text" type="text" readOnly="true"
                           value="<?php echo $typename_text; ?>">
                </div>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd">
                    <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>型号：</label>
                </div>
                <div class="weui-cell__bd">
                    <input class="form-control" name="model" id="model" type="text" readOnly="true" readOnly="true"
                           value="<?php echo $model_sn; ?>">
                </div>
            </div>
            <div class="weui-cells__title"> 故障描述<span class="red">*</span></div>
            <div class="weui-cells ">
                <div class="weui-cell">
                    <div class="weui-cell__bd">
                        <textarea class="form-control" name="content" id="content" placeholder="请输入文本" rows="3"
                                  onkeyup="words_deal();"></textarea>
                        <div class="weui-textarea-counter"><span id="textCount">0</span>/200</div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 开始-->
        <div class="weui-cell" style="background: #fff;">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title text-danger"> 图片上传<span class="red">*</span></p>
                        <div class="weui-uploader__info">0/9</div>
                    </div>

                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">

                        </ul>
                        <div class="weui-uploader__input-box">
                            <input id="uploaderInput" class="weui-uploader__input">
                            <input type="hidden" name="picurls" id="picurls">
                            <input type="hidden" name="picfiles" id="picfiles">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--上传 结束-->
        <input type="hidden" name="action" id="action" value="add"/>
        <input type="hidden" name="uid" id="uid" value="<?php echo $uid ?>"/>

</form>
</div>
<div class="sub_btn"><a href="javascript:;" id="saoma_btn" class="btn btn-danger btn-lg btn-block"
                        onclick="cfm_order2();return false;">立即报修</a></div>
<div class="clear"></div>
<script>
    //描述字数限制
    function words_deal() {
        var curLength = $("#content").val().length;
        if (curLength > 200) {
            var num = $("#content").val().substr(0, 200);
            $("#content").val(num);
            alert("超过字数限制，多出的字将被截断！");
        }
        else {
            $("#textCount").text(200 - $("#content").val().length);
        }
    }


    function cfm_order2() {
        if ($("#school").val() == "") {
            $.toast("单位不能为空", "forbidden");
            $("#school").focus();
            return false;
        }
        if ($("#truename").val() == "") {
            $.toast("联系人不能为空", "forbidden");
            $("#truename").focus();
            return false;
        }
        if ($("#mobile").val() == "") {
            $.toast("手机号码不能为空", "forbidden");
            $("#mobile").focus();
            return false;
        }

        if ($("#content").val() == "") {
            $.toast("请输入故障描述", "forbidden");
            $("#content").focus();
            return false;
        }
        if ($("#picfiles").val() == "") {
            $.toast("请上传故障图片", "forbidden");
            return false;
        }
        $("#saoma_btn").hide();
        $("#form").submit();
    }
</script>

<?php
if (isset($action) and $action == 'add') {
    if (empty($content)) {
        echo '<script type="text/javascript">
	$.toast("操作不正确", function() {
		 window.location.href="index.php";
		});
	</script>';
        exit();
    }

    $address = htmlspecialchars($address);
    $address_name = htmlspecialchars($address_name);
    $json_address = $address . "-" . $school;
    // 工单信息入库
    $typename = htmlspecialchars($typename);
    $content = htmlspecialchars($content);
    $picurls = "";
    $jindu = "1";
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());

    //新建工单
    $sql2 = "insert into `#@__order`(openid,uid,town,school,truename,mobile,address,apply_type,apply_device,title,content,picurls,post_time,jindu,latitude,longitude,accuracy,picfiles,delstate,device_num,apply_address,apply_address_name) values ('$openid','$uid','$town','$school','$truename','$mobile','$address','1','$typename','$title','$content','$picurls','$post_time','$jindu','$latitude','$longitude','$accuracy','$picfiles','','$device_num','$address','$address_name')";

    $dosql->ExecNoneQuery($sql2);


    $orderid = $dosql->GetLastID();
    //插入更新的状态
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,latitude,longitude,accuracy,address,address_name) values ('$orderid','用户报修','$post_time','1','$latitude','$longitude','$accuracy','$address','$address_name')");
    $orderidname = date('Ymd', time()) . "-" . $orderid;
    //封装为json格式的数据
    $json = '{
	  "touser": "' . $openid . '" ,  
	  "template_id": "' . $cfg_apply . '",    
	  "url":"' . $cfg_weburl . 'wx/orderDetail.php?orderid=' . $orderid . '",      
	  "data": {
		  "first": {
			  "value": "您好，报修成功，即将派单维修", 
			  "color": "#f71b03"
		  }, 
		  "keyword1": {
			  "value": "' . $school . '", 
			  "color": "#1aad19"
		  }, 
		  "keyword2": {
			  "value": "' . $mobile . '", 
			  "color": "#1aad19"
		  },
		  "keyword3": {
			  "value":" ' . $json_address . '", 
			  "color": "#0e48cb"
		  },
		  "keyword4": {
			  "value": " ' . $typename . "-" . $title . "-" . $model . '", 
			  "color": "#173177"
		  },
		  "keyword5": {
			  "value": "序列号：' . $device_num . ";" . $content . '", 
			  "color": "#173177"
		  },
		  "remark": {
			  "value": "系统正在派单，请稍等。马上会有工程师和您联系，请保持通讯畅通。服务热线：' . $cfg_hotline . '", 
			  "color": "#f71b03"
		  } 
	  }
	}';
    sendWxMsg($json);

    //封装为json格式的数据
    $json2 = '{
	  "touser": "' . $cfg_openid . '" ,  
	  "template_id": "' . $cfg_apply . '",    
	  "url":"' . $cfg_weburl . 'wx/morderDetail.php?orderid=' . $orderid . '",      
	  "data": {
		  "first": {
			  "value": "您好，用户通过扫码，报修成功，请登录后台处理", 
			  "color": "#f71b03"
		  }, 
		   "keyword1": {
			  "value": "' . $school . '", 
			  "color": "#1aad19"
		  }, 
		  "keyword2": {
			  "value": "' . $mobile . '", 
			  "color": "#1aad19"
		  },
		  "keyword3": {
			  "value":" ' . $json_address . '", 
			  "color": "#0e48cb"
		  },
		  "keyword4": {
			  "value": " ' . $typename . "-" . $title . "-" . $model . '", 
			  "color": "#173177"
		  },
		  "keyword5": {
			  "value": "序列号:' . $device_num . ";" . $content . '", 
			  "color": "#173177"
		  },
		  "remark": {
			  "value": "等登录后台处理，先联系用户，再派单", 
			  "color": "#f71b03"
		  } 
	  }
	}';
    sendWxMsg($json2);

    echo '<script type="text/javascript">
	$.toast("报修成功", function() {
		 window.location.href="order.php";
		});
	</script>';
    exit();

}
?>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
    wx.config({
        debug: false,
        appId: '<?php echo $signPackage["appId"];?>',
        timestamp: <?php echo $signPackage["timestamp"];?>,
        nonceStr: '<?php echo $signPackage["nonceStr"];?>',
        signature: '<?php echo $signPackage["signature"];?>',
        jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'openAddress',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'openLocation',
            'getLocation'
        ]
    });
    wx.ready(function () {
        // 分享
        var urlurl = window.location.href;
        var shareData = {
            title: '<?php echo $cfg_webname;?>-在线报修',
            desc: '在线报修，2小时内响应。48-72小时内完修。维修状态实时查看。',
            link: urlurl,
            imgUrl: '<?php echo $cfg_weburl;?>wx/images/zxbx.jpg'
        };


        wx.onMenuShareAppMessage(shareData);
        wx.onMenuShareTimeline(shareData);
        wx.onMenuShareQQ(shareData);
        wx.onMenuShareQZone(shareData);
        //地址
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                $("#latitude").val(latitude);
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                $("#longitude").val(longitude);
                var speed = res.speed; // 速度，以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                $("#accuracy").val(accuracy);
                $.ajax({
                    url: "getMap.php?l=" + latitude + "&w=" + longitude,
                    type: "GET",
                    timeout: 2000,
                    dataType: "json",
                    success: function (data) {
                        console.log('ok');
                        var gps_address = data.result.address;
                        var address_name = data.result.formatted_addresses.recommend;
                        //alert(gps_address);
                        $("#address").val(gps_address);
                        $("#address_name").val(address_name);
                    },
                    error: function (data) {
                        console.log('error');

                    }
                });
            },
            cancel: function (res) {
                $.alert("你拒绝授权获取地理位置，我们的工程师无法快速定位。时效性可能会延时，请谅解", " 温馨提示");
            }

        });
        //打开相册
        var images = {
            localId: [],
            serverId: []
        };
        var filepaths = "";
        document.querySelector('#uploaderInput').onclick = function () {
            wx.chooseImage({
                count: 9, // 默认9
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var picurls = res.localIds;
                    var uploadCount = 0;
                    var pic_length = res.localIds.length;
                    var m = 0;
                    var upload = function () {
                        wx.uploadImage({
                            localId: picurls[uploadCount],
                            success: function (res) {
                                //如果还有照片，继续上传
                                var serverId = res.serverId; // 返回图片的服务器端ID
                                console.log(serverId);
                                $.ajax({
                                    type: 'POST',
                                    url: "getFile.php",
                                    data: {serverId: serverId},
                                    dataType: 'JSON',
                                    success: function (result) {
                                        if (result.errno == 0) {
                                            console.log(result.msg);
                                            if (result.msg === "ok") {
                                                filepaths += result.filename + ",";
                                                $("#picfiles").val(filepaths);
                                                $("#uploaderFiles").append('<li class="weui-uploader__file" style="background-image:url(' + result.filename + ')"></li>');
                                            } else {
                                                $.alert("上传失败<br/> 请联系管理员！", "温馨提示");
                                            }
                                        }
                                    }
                                });
                                uploadCount++;
                                if (uploadCount < pic_length) {
                                    upload();
                                }
                            }
                        });
                    }
                    upload();
                }
            });
        }
        //


    });
</script>
<?php require_once('footer.php'); ?>